package com.bangcommunity.bbframe.common.utils.crypt;

/**
 * @author tanghc
 * @date 18/7/2
 */
import java.util.concurrent.ThreadLocalRandom;


public class ThreadLocalRandomCodeHelper {
    private static String constantsStr = "0123456789abcdefABCDEF";
    private static String constantsNum = "0123456789";

    public static void setRandomByte(ThreadLocalRandom random,byte[] array){
        random.nextBytes(array);
    }

    public static String randomString(int num){
        ThreadLocalRandom random = ThreadLocalRandom.current();
        StringBuilder sb = new StringBuilder(num);
        byte[] array = new byte[num];
        setRandomByte(random,array);
        for(byte b : array){
            int i = b % constantsStr.length();
            sb.append(constantsStr.charAt(i >=0 ? i : Math.abs(i)));
        }
        return sb.toString();
    }

    public static String randomNum(int num){
        ThreadLocalRandom random = ThreadLocalRandom.current();
        StringBuilder sb = new StringBuilder(num);
        byte[] array = new byte[num];
        setRandomByte(random,array);
        for(byte b : array){
            int i = b % constantsNum.length();
            sb.append(constantsNum.charAt(i >=0 ? i : Math.abs(i)));
        }
        return sb.toString();
    }

    public static String generateTimeStamperRandomStr(){
        StringBuilder sb = new StringBuilder();
        sb.append(randomString(32)).append("-").append(generateTimeStr(4));

        return sb.toString();
    }

    public static String generateTimeStr(int length){
        String str = System.currentTimeMillis() + "";
        if(str.length() < length){
            return str;
        }
        return str.substring(str.length() - length);
    }

    public static void main(String[] args) {
        long b = System.currentTimeMillis();
        for(int i = 0;i<30000;i++){
            System.out.println(randomNum(7));
        }
        System.out.println(randomString(40));
        System.out.println((System.currentTimeMillis() - b));
    }
}
